package slxy.jiangtao.dts.core.common.bean;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;

/**
 * hibernate拦截器
 * Created by JiangTao on 2016/12/29.
 */
@Component("auditInterceptor")
public class AuditInterceptor extends EmptyInterceptor {

    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        return updateProperty(Constants.CREATE_TIME, new Date(), entity, state, propertyNames);
    }

    @Override
    public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
        return updateProperty(Constants.UPDATE_TIME, new Date(), entity, currentState, propertyNames);
    }

    private boolean updateProperty(String field, Object value, Object entity, Object[] state, String[] propertyNames) {
        if (!(entity instanceof BaseEntity)) return false;
        for (int i = 0; i < propertyNames.length; i++) {
            if (field.equals(propertyNames[i])) state[i] = value;
        }
        return true;
    }
}
